package com.aaa.tmr.util;

import com.aaa.tmr.entity.Log;
import com.aaa.tmr.entity.User;
import com.aaa.tmr.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;

/**
 * @author ：Marko
 * @date ：Created in 2021/3/22 18:50
 * @description ：记录查询,页面跳转,图表查看等日志
 * @modified By：
 * @version:
 */
@Aspect
@Component
public class LogUtil {

    @Resource
    private LogService logService;

    @Resource
    private HttpSession session;

    /**
     * description: <br>
     *"execution(* com.aaa.tmr.controller.*.to*(..)) "
     * @param joinpoint
     * @author Marko
     * @Date 2021/3/22 19:03
     **/
    @AfterReturning(pointcut =
            " execution(* com.aaa.tmr.controller.*.query*(..))" +
            "|| execution(* com.aaa.tmr.controller.*.select*(..))")
    public void recordOperLog(JoinPoint joinpoint) {
        Log log = new Log();
        //获取当前登录名
        User user = (User) session.getAttribute("userInfo");
        log.setLoginName(user.getLoginName());
        //获取用户名
        log.setUserName(user.getUserName());
        //获取HttpServletRequest
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取IP
        String remoteAddr = request.getRemoteAddr();
        log.setIp(remoteAddr);
        //带包的类名称 获取类的限定名
        String className = joinpoint.getTarget().getClass().getName();
        log.setClassName(className);
        //获取方法名
        String methodName = joinpoint.getSignature().getName();
        log.setMethodName(methodName);
        //参数
        String params = Arrays.toString(joinpoint.getArgs());
        log.setParams(params);
        //操作时间
        log.setCreateTime(new Date());
        logService.insert(log);
    }
}
